from django.db import models
from django.contrib.auth import get_user_model


class Message(models.Model):
    sender = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name='发送者', related_name='sender')
    receiver = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,
                                 null=True, blank=True, verbose_name='接收者', related_name='receiver')
    content = models.TextField(verbose_name='内容', max_length=10000)
    time = models.DateTimeField(verbose_name='时间', auto_now_add=True)
    read = models.BooleanField(verbose_name='已读', default=False)

    def __str__(self):
        return (f'{self.time.strftime("%Y年%m月%d日 %H时%M分%S秒")} '
                f'{self.sender}发往{self.receiver if self.receiver else "所有人"}的消息')

    class Meta:
        verbose_name = '消息'
        verbose_name_plural = '消息'
        ordering = ('time', 'sender', 'receiver')
